package fr.chronogps.moto.testChrono;

import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

	private Button boutonStart;
	private Button boutonStop;
	private TextView label1;
	private Handler mHandler = new Handler();
	private long mStartTime = 0;
	private Button boutonGotoGps;
	private Context mContext = this;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		label1 = (TextView)findViewById(R.id.Label1);

		boutonStart = (Button)findViewById(R.id.ButtonStart);
		boutonStart.setOnClickListener(mStartListener);
		
		boutonStop = (Button)findViewById(R.id.ButtonStop);
		boutonStop.setOnClickListener(mStopListener);
		
		boutonGotoGps = (Button)findViewById(R.id.ButtonGoToGps);
		boutonGotoGps.setOnClickListener(mGoToGpsListener);

	}


		OnClickListener mStartListener = new OnClickListener() {
			public void onClick(View v) {
				if (mStartTime == 0) {
					mStartTime = SystemClock.uptimeMillis();
					mHandler.removeCallbacks(mUpdateTimeTask);
					mHandler.post(mUpdateTimeTask);	//va dans mUpdateTimeTask
				}
			}
		};
		
		OnClickListener mStopListener = new OnClickListener() {
			public void onClick(View v) {
					mHandler.removeCallbacks(mUpdateTimeTask);
					mStartTime = 0;
			}
		};
		
		OnClickListener mGoToGpsListener = new OnClickListener() {
			public void onClick(View v) {
				Intent defineIntent = new Intent(mContext, Gps.class);
				startActivity(defineIntent);
			}
		};
	
	
		private Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				final long start = mStartTime;
				long curTime = SystemClock.uptimeMillis();
				long millis =  curTime - start;
				int seconds = (int) (millis / 1000);
				int minutes = seconds / 60;
				int heures = minutes / 50;
				seconds     = seconds % 60;
	
				
				DecimalFormat dfSecond = new DecimalFormat("00");
				dfSecond.setMaximumIntegerDigits(2);
				
				DecimalFormat dfMillis = new DecimalFormat("0");
				dfMillis.setMaximumIntegerDigits(1);
				label1.setText(dfSecond.format(heures)+ " h " + dfSecond.format(minutes) + " m " + dfSecond.format(seconds)+" s "+dfMillis.format(millis/100));
				
				mHandler.postAtTime(this, start + millis+100);
			}
		};
}